package vn.vfriends.payment.jpa.controller;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.UserTransaction;
import vn.vfriends.payment.jpa.controller.exceptions.IllegalOrphanException;
import vn.vfriends.payment.jpa.controller.exceptions.NonexistentEntityException;
import vn.vfriends.payment.jpa.controller.exceptions.RollbackFailureException;
import vn.vfriends.payment.jpa.entity.Page;
import vn.vfriends.payment.jpa.entity.Role;

/**
 *
 * @author tuan@vfriends.vn
 */
public class RoleJpaController implements Serializable {

    @Resource
    private UserTransaction utx = null;
    @PersistenceUnit(unitName = "vfPaymentPU")
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Role role) throws RollbackFailureException, Exception {
        if (role.getPages() == null) {
            role.setPages(new ArrayList<Page>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            List<Page> attachedPages = new ArrayList<Page>();
            for (Page pageToAttach : role.getPages()) {
                pageToAttach = em.getReference(pageToAttach.getClass(), pageToAttach.getId());
                attachedPages.add(pageToAttach);
            }
            role.setPages(attachedPages);
            em.persist(role);
            //  Update page and old role
            for (Page page : role.getPages()) {
                Role oldRole = page.getRole();
                page.setRole(role);
                page = em.merge(page);
                if (oldRole != null) {
                    oldRole.getPages().remove(page);
                    oldRole = em.merge(oldRole);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Role role) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Role persistentRole = em.find(Role.class, role.getId());
            List<Page> oldPages = persistentRole.getPages();
            List<Page> newPages = role.getPages();
            List<String> illegalOrphanMessages = null;
            //  Check old pages
            for (Page oldPage : oldPages) {
                if (!newPages.contains(oldPage)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Page " + oldPage + " since its role field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            //  Verify new pages
            List<Page> attachedNewPages = new ArrayList<Page>();
            for (Page newPageToAttach : newPages) {
                newPageToAttach = em.getReference(newPageToAttach.getClass(), newPageToAttach.getId());
                attachedNewPages.add(newPageToAttach);
            }
            newPages = attachedNewPages;
            role.setPages(newPages);
            
            role = em.merge(role);
            //  Update new pages
            for (Page newPage : newPages) {
                if (!oldPages.contains(newPage)) {
                    Role oldRole = newPage.getRole();
                    newPage.setRole(role);
                    newPage = em.merge(newPage);
                    if (oldRole != null && !oldRole.equals(role)) {
                        oldRole.getPages().remove(newPage);
                        oldRole = em.merge(oldRole);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Long id = role.getId();
                if (findRole(id) == null) {
                    throw new NonexistentEntityException("The role with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Long id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Role role;
            try {
                role = em.getReference(Role.class, id);
                role.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The role with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Page> pagesOrphanCheck = role.getPages();
            for (Page pagesOrphanCheckPage : pagesOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Role (" + role + ") cannot be destroyed since the Page " + pagesOrphanCheckPage + " in its pages field has a non-nullable role field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(role);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Role> findRoles() {
        return findRoles(true, -1, -1);
    }

    public List<Role> findRoles(int maxResults, int firstResult) {
        return findRoles(false, maxResults, firstResult);
    }

    private List<Role> findRoles(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Role.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Role findRole(Long id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Role.class, id);
        } finally {
            em.close();
        }
    }

    public Role findRoleByName(String name) {
        EntityManager em = getEntityManager();
        try {
            Query query = em.createNamedQuery("Role.findByName", Role.class);
            query.setParameter("name", name);
            List<Role> roleList = query.getResultList();
            if (roleList != null && !roleList.isEmpty()) {
                return roleList.get(0);
            } else {
                return null;
            }
        } finally {
            em.close();
        }
    }
    
    public Role findRoleByCode(Role.RoleCode code) {
        EntityManager em = getEntityManager();
        try {
            Query query = em.createNamedQuery("Role.findByCode", Role.class);
            query.setParameter("code", code);
            List<Role> roleList = query.getResultList();
            if (roleList != null && !roleList.isEmpty()) {
                return roleList.get(0);
            } else {
                return null;
            }
        } finally {
            em.close();
        }
    }
    
    public List<Role> findRolesByUserEmail(String email) {
        EntityManager em = getEntityManager();
        try {
            CriteriaBuilder builder = em.getCriteriaBuilder();
            CriteriaQuery<Role> criteria = builder.createQuery(Role.class);
            Root<Role> root = criteria.from(Role.class);
            
            Predicate predicate = builder.conjunction();
            predicate = builder.and(predicate, builder.isMember(email, root.<Set<String>>get("userEmails")));
            
            criteria.where(predicate);
            
            Query query = em.createQuery(criteria);
            return query.getResultList();
        } finally {
            em.close();
        }
    }
    
    public int getRoleCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Role> rt = cq.from(Role.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
